<template>
  <div class="llm-qa-widget">
    <div class="qa-history-panel" ref="historyPanel">
      <div v-for="(message, index) in messages" :key="index" :class="['message-row', message.sender]">
        <div class="message-bubble">
          <div class="message-content">
            <p>{{ message.text }}</p>
          </div>
          <div class="message-timestamp">
            {{ new Date(message.timestamp).toLocaleTimeString() }}
          </div>
        </div>
      </div>
      <!-- 流式输出的临时消息 -->
      <div v-if="isLoading && streamingMessage" class="message-row ai">
        <div class="message-bubble">
          <div class="message-content">
            <p>{{ streamingMessage }}</p>
          </div>
          <div class="message-timestamp">
            {{ new Date().toLocaleTimeString() }}
          </div>
        </div>
      </div>
    </div>
    <div class="qa-input-panel">
      <el-input
        v-model="question"
        placeholder="提出您的问题..."
        @keydown.enter.prevent="sendMessage"
        resize="none"
      >
        <template #append>
          <el-button @click="sendMessage" :loading="isLoading">
            <el-icon><Promotion /></el-icon>
          </el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Promotion } from '@element-plus/icons-vue';
import aiInteraction from '@/utils/ai-interaction';

const question = ref('');
const isLoading = ref(false);
const messages = ref([
  {
    sender: 'ai',
    text: '你好！我是您的智能问答助手，可以解答关于免疫组学分析的常见问题。',
    timestamp: new Date(),
  }
]);
const historyPanel = ref(null);
const streamingMessage = ref(''); // 用于流式输出的临时消息

const sendMessage = async () => {
  if (!question.value.trim()) {
    ElMessage.warning('问题不能为空');
    return;
  }

  // 添加用户消息到历史记录
  messages.value.push({
    sender: 'user',
    text: question.value,
    timestamp: new Date(),
  });

  isLoading.value = true;
  const currentQuestion = question.value;
  question.value = ''; // 清空输入

  // 初始化流式消息
  streamingMessage.value = '';
  
  try {
    // 使用流式AI API调用
    await aiInteraction.callAIStream(
      `你是一个肿瘤免疫数据处理专家，请回答以下问题：${currentQuestion}`,
      (chunk) => {
        // 处理每个接收到的文本块
        streamingMessage.value += chunk;
        // 自动滚动到底部
        nextTick(() => {
          if (historyPanel.value) {
            historyPanel.value.scrollTop = historyPanel.value.scrollHeight;
          }
        });
      }
    );
    
    // 流式传输完成后，将完整消息添加到消息历史中
    messages.value.push({
      sender: 'ai',
      text: streamingMessage.value,
      timestamp: new Date(),
    });
    
    // 清空流式消息
    streamingMessage.value = '';
  } catch (error) {
    console.error('AI调用出错:', error);
    
    // 显示错误消息
    const errorMessage = '抱歉，AI助手暂时无法回答您的问题，请稍后重试。';
    messages.value.push({
      sender: 'ai',
      text: errorMessage,
      timestamp: new Date(),
    });
    
    // 清空流式消息
    streamingMessage.value = '';
  }

  isLoading.value = false;
};

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    if (historyPanel.value) {
      historyPanel.value.scrollTop = historyPanel.value.scrollHeight;
    }
  });
}, { deep: true });
</script>

<style scoped>
.llm-qa-widget {
  display: flex;
  flex-direction: column;
  height: 400px; /* Or adjust as needed */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.qa-history-panel {
  flex-grow: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message-row {
  display: flex;
  margin-bottom: 15px;
}

.message-row.user {
  justify-content: flex-end;
}

.message-row.ai {
  justify-content: flex-start;
}

.message-bubble {
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 18px;
}

.message-row.user .message-bubble {
  background-color: #409eff;
  color: white;
  border-top-right-radius: 5px;
}

.message-row.ai .message-bubble {
  background-color: #ffffff;
  color: #303133;
  border: 1px solid #e4e7ed;
  border-top-left-radius: 5px;
}

.message-content p {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.message-timestamp {
  font-size: 0.7em;
  color: #c0c4cc;
  margin-top: 5px;
  text-align: right;
}
.message-row.user .message-timestamp {
    color: #a2cfff;
}

.qa-input-panel {
  padding: 10px;
  border-top: 1px solid #dcdfe6;
  background-color: #fff;
}
</style>